﻿
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraBars;
using CTEM.Models;
using CTEM.Controllers.BUS;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraEditors.DXErrorProvider;
using CTEM.Controllers.Global;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraEditors.Controls;

namespace CTEM.ModuleForms.ManageWorker
{
    public partial class WorkersSalaryDetail : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        private bool _isNew;
        private bool _isUpdate;
        private bool _isEdit;
        public DayWorking _dayWorkingFrom;
     
        private WorkerBUS _workerBUS;
        private List<WorkerDTO> _listWorkerSalary;
        private List<WorkerDTO> _listSalaryHistory;
        private WorkerSalaryDTO _workersalary;
        private List<DayWorkingDTO> _dayWorking;
        
        public WorkersSalaryDetail(WorkerSalaryDTO workersalary)
        {
            _dayWorking = TimeForWorkingDay(workersalary);
           
            _listWorkerSalary = new List<WorkerDTO>();
            _listSalaryHistory = new List<WorkerDTO>();
            _workerBUS = new WorkerBUS();
            _workersalary = workersalary;
            InitializeComponent();
        
            loadAllworker();
        }
        public void loadAllworker()
        {
          
            List<WorkerDTO> listWorker = new List<WorkerDTO>();

            try
            {
                listWorker = _workerBUS.LoadAllWks(_workersalary.WorkersSalaryID);
            
                WorkerBindingSource1.DataSource = listWorker;
                 
                 
            }
            catch
            { }
        }
  

        private void gridView1_InvalidValueException(object sender, DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs e)
        {
            e.ErrorText = "Giá trị bạn nhập không hợp lệ"; 
        }

        private List<DayWorkingDTO> TimeForWorkingDay(WorkerSalaryDTO workerSalary)
        {
            List<DayWorkingDTO> listDayworking = new List<DayWorkingDTO>();
            TimeSpan numdatespan = workerSalary.ToDate - workerSalary.FromDate;
            int numdates = numdatespan.Days;
            for (int i = 0; i <= numdates; i++)
            {
                DayWorkingDTO dayworking = new DayWorkingDTO();
                dayworking.Date = workerSalary.FromDate.AddDays(i);
                listDayworking.Add(dayworking);
            }
            return listDayworking;
        }


        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            _isNew = true;
            gridView1.SetRowCellValue(e.RowHandle, "CreatedDate", DateTime.Today);
            gridView1.SetRowCellValue(e.RowHandle, "LastUpdate", DateTime.Today);
       
        }

        public bool ValidateWorker(WorkerDTO worker, out string message, out int pos)
        {
            if (worker.Salary <= 0)
            {
                message = "bạn chưa nhập giá công nhật cho nhân viên";
                pos = 3;
                return false;
            }
            if (worker.Fullname == null || worker.Fullname == "")
            { 
                message = "bạn chưa nhập tên công nhân";
                pos = 1;
                return false;
            }
            else if (worker.Position == null || worker.Position == "")
            {
                message = "bạn chưa nhập chức vụ cho công nhân";
                pos = 2;
                return false;
            }

            message = "";
            pos = 0;
            return true;
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (_isNew)
            {
                int rowIndex = gridView1.FocusedRowHandle;
                var view = sender as ColumnView;
                var worker = e.Row as WorkerDTO;
                worker.WorkersSalaryID = _workersalary.WorkersSalaryID;

                string message;
                long workerID = 0;
                int pos;

                if (!ValidateWorker(worker, out message, out pos))
                {
                    e.Valid = false;
                    if (view != null)
                    {

                        view.ClearColumnErrors();
                        view.SetColumnError(view.Columns[pos], message, ErrorType.Warning);
                    }
                    DialogResult result = MessageBox.Show(message + "\nBạn có muốn nhập lại thông tin", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result == DialogResult.No)
                    {
                        _isNew = false;
                        e.Valid = true;
                        loadAllworker();
                    }
                }
                else
                {
                    workerID = _workerBUS.CreateWks(worker);
                    if (workerID <= 0)
                    {
                        MessageBox.Show("xem lại kết nối máy bạn tới server", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                       
                        _isNew = false;
                        _isUpdate = false;
                        loadAllworker();
                    }

                    else
                    {
                        try
                        {
                            foreach (var dayWorking in _dayWorking)
                            {
                                dayWorking.WorkerID = workerID;
                                _workerBUS.CreateDayWorking(dayWorking);
                            }
                            alertControlMain.Show(this, Constants.CONFIRM, String.Format("Bạn Đã tạo mới công nhân: {0} Thành Công!", worker.Fullname));
                            worker.WorkerID = workerID;
                            var oldEmployeeSalary = _workerBUS.LoadWorkerByID(worker.WorkerID);
                            _isUpdate = false;
                            _isNew = false;
                            
                            if (oldEmployeeSalary != null)
                            {
                                oldEmployeeSalary.Status = 2;
                                _listSalaryHistory.Add(oldEmployeeSalary);
                            }
                            loadAllworker();
                        }
                        catch 
                        {
                            _workerBUS.delete(workerID);
                            MessageBox.Show("xem lại kết nối máy bạn tới server", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                         
                                _isNew = false;
                                e.Valid = true;
                                loadAllworker();
                           
                         }
                    }
                }
            }
        }
   
        
        public List<WorkerDTO> loadListWorker()
        {
            return _listWorkerSalary;
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle)
            {

                gridView1.OptionsBehavior.ReadOnly = false;
                _isNew = true;

            }
            else
            {
                _isNew = false;

                gridView1.OptionsBehavior.ReadOnly = !_isEdit;

            }
        }

        private void WorkersSalaryDetail_Load(object sender, EventArgs e)
        {
            Global.InitLayoutGridView(gridView1);
            loadAllworker();
            _isEdit = false;
            
        }

        private void gridView1_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (!_isNew)
            {
                var view = sender as ColumnView;
                var i = e.RowHandle;
                var worker = gridView1.GetRow(i) as WorkerDTO;


                if (worker != null)
                {



                    string message;
                    int pos;
                    if (!ValidateWorker(worker, out message, out pos))
                    {
                        DialogResult result = MessageBox.Show(message + "\nBạn có muốn nhập lại thông tin", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        view.SetColumnError(view.Columns[pos], message, ErrorType.Warning);
                        if (result == DialogResult.No)
                        {
                            _isUpdate = false;
                            view.ClearColumnErrors();
                            loadAllworker();
                            return;
                        }
                        else
                        {
                            _isUpdate = true;
                            gridView1.FocusedRowHandle = i;
                            gridView1.FocusedColumn = e.Column;
                            return;
                        }
                    }
                    var oldEmployeeSalary = _workerBUS.LoadWorkerByID(worker.WorkerID);
                
                    if (!_workerBUS.updateWks(worker))
                    {
                        MessageBox.Show("Không thể cập nhật thông tin", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        _isUpdate = false;
                    }
                    else
                    {
                        alertControlMain.Show(this, Constants.CONFIRM, String.Format("Bạn Đã sửa bản chấm công cho công nhân {0} Thành Công!", worker.Fullname));
                     
                        _isUpdate = false;
                        _isNew = false;
                        loadAllworker();
                        if (oldEmployeeSalary != null)
                        {
                            oldEmployeeSalary.Status = 2;
                            _listSalaryHistory.Add(oldEmployeeSalary);
                        }
                    }
                }
            }
        }

        private void WorkersSalaryDetail_FormClosed(object sender, FormClosedEventArgs e)
        {
            List<WorkerDTO> workers = new List<WorkerDTO>();
            workers = _workerBUS.LoadAllWks(_workersalary.WorkersSalaryID);
            _workersalary.TotalSalary = 0;
            foreach (var worker in workers)
            {
                _workersalary.TotalSalary += worker.TotalSalary;
            }
            WorkerSalaryBUS ws = new WorkerSalaryBUS();
            ws.UpdateWks(_workersalary);

        }

        private void repositoryItemButtonEdit1_Click(object sender, EventArgs e)
        {
            int rowIndex = gridView1.FocusedRowHandle;
            var view = sender as ColumnView;
            var worker = gridView1.GetRow(rowIndex) as WorkerDTO;
            if (worker != null)
            {
                if (worker.WorkerID > 0)
                {
                    DayWorking dayworking = new DayWorking(worker);
                    dayworking.ShowDialog();
                }
                else
                    MessageBox.Show("Bạn phải khởi tạo bảng lương trước khi thực hiện chức năng này.");
            }

            else
                MessageBox.Show("Bạn phải khởi tạo bảng lương trước khi thực hiện chức năng này.");
        }

        private void bntEdit_ItemClick(object sender, ItemClickEventArgs e)
        {
            gridView1.OptionsBehavior.ReadOnly = false;
        }

        private void bntDelete_ItemClick(object sender, ItemClickEventArgs e)
        {
            int rowIndex = gridView1.FocusedRowHandle;
            var worker = gridView1.GetRow(rowIndex) as WorkerDTO;
            if (worker != null)
                if (MessageBox.Show(string.Format("Bạn có chắc chắn muốn xóa không?"), "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    // -- load current data for undo funciton--

                    WorkerDTO oldWorker = worker;
                    oldWorker.dayWorking = _workerBUS.LoadAllDaysWorking(oldWorker.WorkerID);
                    if (oldWorker != null)
                    {
                        oldWorker.Status = 3;
                        _listSalaryHistory.Add(oldWorker);
                    }
                    _workerBUS.delete(worker.WorkerID);
                    alertControlMain.Show(this, Constants.CONFIRM, String.Format("Bạn Đã xóa bảng lương công nhân {0} Thành Công!", worker.Fullname));
                    loadAllworker();
                }
        }

        private void bntUndo_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (_listSalaryHistory.Count > 0)
            {
                try
                {
                    WorkerDTO worker = _listSalaryHistory[_listSalaryHistory.Count - 1];
                    if (worker.Status == 1)
                    {
                        _workerBUS.delete(worker.WorkerID);
                    }
                    else if (worker.Status == 2)
                    {
                        _workerBUS.updateWks(worker);
                    }
                    else if (worker.Status == 3)
                    {
                        worker.WorkerID = _workerBUS.CreateWks(worker);
                        foreach (var day in worker.dayWorking)
                        {
                            day.WorkerID = worker.WorkerID;
                            _workerBUS.CreateDayWorking(day);
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("Không thể hồi phục dữ liệu này");
                }
                _listSalaryHistory.RemoveAt(_listSalaryHistory.Count - 1);
            }
            loadAllworker();
        }

        private void gridView1_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = ExceptionMode.NoAction;
        }

      
    
    }
}